const {desktopCapturer} = window.require('electron');

const video =  document.getElementById('screen-video');

function play(stream) {
    video.srcObject =  stream;
    video.onloadedmetadata = () => {
        video.play();
    }
}

function getScreenStream() {
    return new Promise((resolve, reject) => {
        desktopCapturer.getSources({
            types: ['screen']
        }).then(async sources => {
            console.log('source', sources);
            for (let source of sources) {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({
                        audio: false,
                        video: {
                            mandatory: {
                                chromeMediaSource: 'desktop',
                                chromeMediaSourceId: source.id,
                                maxHeight: 400,
                                maxHeight: 400
                            }
                        }
                    });
                    play(stream);
                }
                catch (e) {
                    console.error('navigator.mediaDevices.getUserMedia', e);
                }
            }
        });
    });
}

// getScreenStream();
const pc = new window.RTCPeerConnection({});
async function createAnswer(offer) { // 回应函数
    const screenStream = await getScreenStream();
    pc.addStream(screenStream);
    await pc.setRemoteDescription(offer);
    await pc.setLocalDescription(await pc.createAnswer());
    console.log('answer', JSON.stringify(pc.localDescription));
    return pc.localDescription;
}

window.createAnswer = createAnswer;




